<template>
  <div class="app-container">
    <!-- 基本信息 -->
    <p><b>测试步骤名称</b></p>
    <el-input v-model="stepForm.name" style="padding: auto" />
    <p style="margin-top: 10px"><b>请求地址</b></p>
    <el-row>
      <el-col :span="4">
        <div style="padding: auto">
          <el-select v-model="method">
            <el-option v-for="item in methodOptions" :key="item.index" :label="item.value" :value="item.index" />
          </el-select>
        </div>
      </el-col>
      <el-col :span="20">
        <div>
          <el-input v-model="url" />
        </div>
      </el-col>
    </el-row>
    <!-- 参数信息-->
    <p><b>请求参数信息</b></p>
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="请求头部" name="headers">
        <el-button type="primary" icon="el-icon-plus" size="small" style="margin-bottom: 5px" @click="addHeader(headersList)" />
        <el-table :data="headersList" border>
          <el-table-column label="参数名" prop="name">
            <template slot-scope="scope">
              <el-select v-model="scope.row.name" value="scope.row.name">
                <el-option v-for="item in headerOptions" :key="item.index" :label="item.value" :value="item.index" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="参数值" prop="value">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="paramsBound(scope)">参数绑定</el-button>
              <el-button type="danger" size="small" @click="deleteParam(scope.$index, headersList)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="请求参数" name="params">
        <el-button type="primary" icon="el-icon-plus" size="small" style="margin-bottom: 5px" @click="addParams" />
        <el-table :data="paramsList" border>
          <el-table-column label="参数名" prop="name">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" />
            </template>
          </el-table-column>
          <el-table-column label="参数值" prop="value">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="paramsBound(scope)">参数绑定</el-button>
              <el-button type="danger" size="small" @click="deleteParam(scope.$index, paramsList)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!-- 响应参数 -->
    <p><b>响应参数</b></p>
    <el-tabs v-model="returnActiveName" type="card">
      <el-tab-pane label="返回头部" name="returnHeaders">
        <el-button type="primary" icon="el-icon-plus" size="small" style="margin-bottom: 5px" @click="addHeader(returnListHeaders)" />
        <el-table :data="returnListHeaders" border>
          <el-table-column label="参数名" prop="name">
            <template slot-scope="scope">
              <el-select v-model="scope.row.name" value="scope.row.name">
                <el-option v-for="item in headerOptions" :key="item.index" :label="item.value" :value="item.index" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="参数值" prop="value">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="danger" size="small" @click="deleteParam(scope.$index, returnListHeaders)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="返回结果" name="returnBody">
        <el-button type="primary" size="small" @click="addReturnListBodyItem">添加返回参数</el-button>
        <el-table
          :data="returnListBody"
          style="width: 100%;margin-bottom: 20px"
          row-key="id"
          border
          default-expand-all
        >
          <el-table-column prop="id" label="ID" />
          <el-table-column label="参数名" prop="name">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" />
            </template>
          </el-table-column>
          <el-table-column label="参数类型" prop="type">
            <template slot-scope="scope">
              <el-select v-model="scope.row.type">
                <el-option v-for="item in returnParamsType" :key="item.index" :label="item.value" :value="item.index" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="参数说明" prop="value">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="addReturnParamsChildren(scope.row)">添加子字段</el-button>
              <el-button type="text" size="mini" @click="deleteParam(scope.$index, returnListBody)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :visible.sync="paramsDialogVisible">
      <el-table border>
        <el-table-column label="操作步骤" prop="name">
          <ul>
            <li v-for="item in boundParamsList" :key="item.id">
              <template slot-scope="scope">
                <span>{{ scope.name }}</span>
              </template>
            </li>
          </ul>
        </el-table-column>
        <el-table-column label="参数位置">
          <template slot-scope="scope">
            <!-- <el-select
              v-if="scope.row.type === 'interface'"
              value=""
              @change="((val) => {changePreParamsList(val, scope.row)})"
            >
              <el-option v-for="(index, value) in boundInterfaceParamsPositionType" :key="value" :label="index" :value="value" />
            </el-select>
            <span v-else>{{ scope.row.paramsPosition }}</span> -->
            <ul>
              <li @click="getPreStep">1111</li>
              <li>2222</li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column label="参数">
          <el-tree
            ref="tree"
            :data="preParamsList"
            show-checkbox
            node-key="id"
            default-expand-all
            highlight-current
            :props="defaultProps"
            @check-change="parentModules"
          >
            <span slot-scope="{ node, data }">
              <span>{{ data.name }}</span>
            </span>
          </el-tree>
        </el-table-column>
      </el-table>
    </el-dialog>
    <div slot="footer" class="dialog-footer">
      <el-button @click="this.$router.go(-1)">
        取消
      </el-button>
      <el-button type="primary" @click="isEdit?updateData():createData()">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getStep, getPreSteps, getCaseSteps, createStep, updateStep } from '@/api/step'
const defaultForm = {
  id: undefined,
  name: '',
  case: 0,
  step_num: 0,
  step_info: '',
  type: 'interface',
  params: '',
  expect: '',
  return_values: '',
  remark: ''
}
export default {
  name: 'InterfaceDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tempRoute: {},
      stepId: 0,
      stepForm: Object.assign({}, defaultForm),
      method: 'get',
      url: '',
      activeName: 'headers',
      returnActiveName: 'returnHeaders',
      headersList: [],
      paramsList: [],
      returnListHeaders: [],
      returnListBody: [],
      paramsDialogVisible: false,
      methodOptions: [
        {
          index: 'get',
          value: 'GET'
        },
        {
          index: 'post',
          value: 'POST'
        },
        {
          index: 'put',
          value: 'PUT'
        },
        {
          index: 'patch',
          value: 'PATCH'
        },
        {
          index: 'delete',
          value: 'DELETE'
        }
      ],
      headerOptions: [
        {
          index: 'Authorization',
          value: 'Authorization'
        },
        {
          index: 'User-Agent',
          value: 'User-Agent'
        },
        {
          index: 'Accept-Language',
          value: 'Accept-Language'
        },
        {
          index: 'Cookie',
          value: 'Cookie'
        }
      ],
      returnParamsType: [
        {
          index: 'Object',
          value: 'Object'
        },
        {
          index: 'Array',
          value: 'Array'
        },
        {
          index: 'Int',
          value: 'Int'
        },
        {
          index: 'String',
          value: 'String'
        },
        {
          index: 'Bool',
          value: 'Bool'
        }],
      boundInterfaceParamsPositionType: {
        'headersList': '请求头部',
        'paramsList': '请求体',
        'returnListHeaders': '返回头部',
        'returnListBody': '返回参数'
      },
      boundParamsList: [],
      defaultProps: {
        children: 'children',
        name: 'name'
      },
      uniqueValue: '',
      preParamsList: []
    }
  },
  created() {
    this.stepId = this.$route.params && this.$route.params.id
    if (this.isEdit) {
      this.getData(this.stepId)
    } else {
      this.tempRoute = Object.assign({}, this.$route)
    }
  },
  methods: {
    getData(id) {
      getStep(id).then(response => {
        this.stepForm = Object.assign({}, response.data)
        this.method = JSON.parse(response.data.step_info).method
        this.url = JSON.parse(response.data.step_info).url
        this.paramsList = JSON.parse(response.data.params).paramsList
        this.headersList = JSON.parse(response.data.params).headersList
        this.returnListBody = JSON.parse(response.data.return_values).returnListBody
        this.returnListHeaders = JSON.parse(response.data.return_values).returnListHeaders
      })
    },
    getCurrentTime() {
      const date = new Date()
      return date.getTime()
    },
    addReturnListBodyItem() {
      const id = this.getCurrentTime()
      const returnListBodyItem = {
        id: id,
        name: '',
        type: 'Object',
        value: '',
        children: []
      }
      this.returnListBody.push(returnListBodyItem)
      console.log('this.returnListBody:', this.returnListBody)
    },
    getPreStep() {
      const params = {
        case: this.isEdit ? this.stepForm.case : this.stepId,
        page: 1,
        limit: 20
      }
      console.log('this.stepForm:', this.stepForm)
      if (this.isEdit) {
        params.step = this.stepForm.step_num
      }
      console.log('params: ', params)
      getPreSteps(params).then(response => {
        this.boundParamsList = response.results
      })
    },
    parentModules(data, checkbox, node) {
      if (checkbox) {
        this.$refs.tree.setCheckedKeys([data.moduldCode])
        this.uniqueValue = this.$refs.tree.getCheckedKeys()
      } else {
        this.uniqueValue = this.$refs.tree.getCheckedKeys()
        if (this.uniqueValue.length === 0) {
          this.uniqueValue = ''
        }
      }
    },
    changePreParamsList(val, row) {
      const tempData = {
        'headersList': JSON.parse(row.params).headersList,
        'paramsList': JSON.parse(row.params).paramsList,
        'returnListHeaders': JSON.parse(row.return_values).returnListHeaders,
        'returnListBody': JSON.parse(row.return_values).returnListBody
      }
      console.log('val: ', val)
      console.log('tempData: ', tempData[val])
      this.preParamsList = [...tempData[val]]
    },
    addReturnParamsChildren(r) {
      r.type = 'Object'
      const id = this.getCurrentTime()
      const childrenItem = {
        id: id,
        name: '',
        type: 'Object',
        value: '',
        children: []

      }
      r.children.push(childrenItem)
      // const item = this.returnListBody.find(item => item.id === r.id)
      // item.children.push(childrenItem
      this.returnListBody = [...this.returnListBody]
      console.log('item status:', r)
      // this.$set
      console.log('this.returnListBody:', this.returnListBody)
    },
    paramsBound(row) {
      this.getPreStep()
      this.paramsDialogVisible = true
    },
    addHeader(attr) {
      const headerItem = {
        name: '',
        value: ''
      }
      attr.push(headerItem)
    },
    collectStepForm() {
      const stepInfo = {
        method: this.method,
        url: this.url
      }
      const params = {
        paramsList: this.paramsList,
        headersList: this.headersList
      }
      const return_values = {
        returnListHeaders: this.returnListHeaders,
        returnListBody: this.returnListBody
      }
      this.stepForm.return_values = JSON.stringify(return_values)
      this.stepForm.step_info = JSON.stringify(stepInfo)
      this.stepForm.params = JSON.stringify(params)
    },
    createData() {
      console.log('创建step数据')
      this.collectStepForm()
      this.stepForm.case = this.stepId
      createStep(this.stepForm).then((response) => {
        if (response) {
          console.log('创建step成功')
          this.$router.go(-1)
        }
      })
    },
    updateData() {
      console.log('更新step数据')
      this.collectStepForm()
      updateStep(this.stepId, this.stepForm).then(response => {
        if (response) {
          this.$notify({
            title: '提示',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
          this.$router.go(-1)
        } else {
          this.$notify({
            title: '提示',
            message: '更新失败',
            type: 'error',
            duration: 1000
          })
        }
      })
    },
    deleteParam(index, rows) {
      console.log('删除参数')
      rows.splice(index, 1)
    },
    addParams() {
      const paramsItem = {
        name: '',
        type: '',
        value: ''
      }
      this.paramsList.push(paramsItem)
    }
  }
}
</script>

<style scoped>
</style>
